#!/bin/bash

set -eo pipefail

maxbootcount=2

source /usr/libexec/bazzite-boot-remount

remount_boot_rw

if ! /usr/bin/grub2-editenv - set boot_success=1; then
    remount_boot_ro
    exit 1
fi

if ! /usr/bin/grub2-editenv - set boot_indeterminate=0; then
    remount_boot_ro
    exit 1
fi

if  [ ! -f /usr/bin/bootc ] ||
    [ "$(sudo /usr/bin/bootc status --json | jq ".status.rollback")" == "null" ]; then
    if ! /usr/bin/grub2-editenv - unset boot_counter; then
        remount_boot_ro
        exit 1
    fi
    echo "Marking boot as succeeded, setting boot_success=1 and unsetting boot_counter (missing rollback)"
else
    if ! /usr/bin/grub2-editenv - set boot_counter="$maxbootcount"; then
        remount_boot_ro
        exit 1
    fi
    echo "Marking boot as succeeded, setting boot_counter=$maxbootcount and boot_success=1"
fi
